<template>
    <el-container class="layout-container-demo" style="height: 100vh">
        <el-aside width="200px">
            <el-scrollbar>
                <h5 class="mb-2"
                    style="font-size: 22px; color: #409eff; line-height: 60px ;width: 200px;text-align: center;">
                    商品管理系统
                </h5>
                <el-menu default-active="1" class="el-menu-vertical-demo">
                    <el-menu-item index="1" @click="() => $router.push('/home')">
                        <el-icon>
                            <House />
                        </el-icon>
                        <span>首页</span>
                    </el-menu-item>
                    <el-menu-item index="2" @click="() => $router.push('/home/user')">
                        <el-icon>
                            <el-icon>
                                <User />
                            </el-icon>
                        </el-icon>
                        <span>用户管理</span>
                    </el-menu-item>
                    <el-menu-item index="3" @click="() => $router.push('/home/goods')">
                        <el-icon>
                            <el-icon>
                                <Notebook />
                            </el-icon>
                        </el-icon>
                        <span>商品管理</span>
                    </el-menu-item>
                    <el-menu-item index="4" @click="() => $router.push('/home/book')">
                        <el-icon>
                            <el-icon>
                                <Star />
                            </el-icon>
                        </el-icon>
                        <span>商品推荐</span>
                    </el-menu-item>
                    <el-menu-item index="5" @click="() => $router.push('/home/borrow')">
                        <el-icon>
                            <el-icon>
                                <Collection />
                            </el-icon>
                        </el-icon>
                        <span>购物车</span>
                    </el-menu-item>
                    <el-menu-item index="6" @click="() => $router.push('/home/feedback')">
                        <el-icon>
                            <el-icon>
                                <CircleCheck />
                            </el-icon>
                        </el-icon>
                        <span>用户反馈</span>
                    </el-menu-item>
                    <el-menu-item index="7" @click="() => $router.push('/home/statement')">
                        <el-icon>
                            <el-icon>
                                <DataAnalysis />
                            </el-icon>
                        </el-icon>
                        <span>报表统计</span>
                    </el-menu-item>
                </el-menu>
            </el-scrollbar>
        </el-aside>
        <el-container>
            <el-header style="height: 5vh">
                <span style="float: right; ">
                    <el-dropdown style="margin-top: 10px;margin-right:5px; cursor: pointer;">
                        <el-icon color="white" size="20px"
                            style="width: 35px;height: 35px;background-color: #409eff; border-radius: 100%;">
                            <UserFilled />
                        </el-icon>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item command="1" @click="() => {
                                    userisvisible = true

                                }">
                                    <el-icon>
                                        <Avatar />
                                    </el-icon>
                                    个人资料
                                </el-dropdown-item>
                                <el-dropdown-item command="2" @click="() => {
                                    isVisible = true
                                }">
                                    <el-icon>
                                        <EditPen />
                                    </el-icon>
                                    修改密码
                                </el-dropdown-item>
                                <el-dropdown-item command="3" @click="ExitSystem">
                                    <el-icon>
                                        <SwitchButton />
                                    </el-icon>
                                    退出登录
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                    <el-badge is-dot class="item" style="margin-top: 17px;margin-left: 20px;cursor: pointer;" @click="() => {
                        isNews = true
                    }">
                        <el-icon color="#409eff" size="20">
                            <Message />
                        </el-icon>
                    </el-badge>
                    <div
                        style="float:right;line-height: 55px;margin-left: 20px; font-family:electronicFont;color:#409eff;margin-right: 10px">
                        {{ nowTime }}
                    </div>
                </span>
            </el-header>
            <el-main>
                <el-scrollbar>
                    <router-view />
                </el-scrollbar>
            </el-main>
        </el-container>
    </el-container>
    <el-dialog v-model='userisvisible' title="个人信息" width="500" top="10vh">
        <el-form ref="userruleFormRef" style="max-width: 400px;margin: 0 auto" :model="user" :rules="userrules"
            label-width="auto" class="demo-ruleForm">
            <el-form-item label="用户名：" prop="username">
                <el-input v-model="user.username" autocomplete="off" placeholder="请输入用户名" />
            </el-form-item>
            <el-form-item label="姓名：" prop="name">
                <el-input v-model="user.name" autocomplete="off" placeholder="请输入姓名" />
            </el-form-item>
            <el-form-item label="性别：" prop="sex">
                <el-select v-model="user.sex" placeholder="请选择性别">
                    <el-option label="男" value="1" />
                    <el-option label="女" value="0" />
                </el-select>
            </el-form-item>
            <el-form-item label="生日：" prop="birthday">
                <el-date-picker v-model="user.birthday" type="date" placeholder="选择日期" />
            </el-form-item>
            <el-form-item label="电话：" prop="tel">
                <el-input v-model="user.tel" autocomplete="off" placeholder="请输入电话" />
            </el-form-item>
            <el-form-item label="邮箱：" prop="email">
                <el-input v-model="user.email" autocomplete="off" placeholder="请输入邮箱" />
            </el-form-item>
            <el-form-item label="角色：" prop="role">
                <el-select v-model="user.role" placeholder="请选择角色">
                    <el-option label="管理员" value="0" />
                    <el-option label="普通用户" value="1" />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="submitUserForm(userruleFormRef)">
                    提交
                </el-button>
                <el-button @click="userisvisible = false">取消</el-button>
            </div>
        </template>
    </el-dialog>
    <el-dialog v-model='isVisible' title="修改密码" width="500" top="25vh">
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="userpassword" status-icon :rules="rules"
            label-width="auto" class="demo-ruleForm">
            <el-form-item label="原密码：" prop="oldpassword">
                <el-input v-model="userpassword.oldpassword" type="password" show-password autocomplete="off"
                    placeholder="请输入原密码" />
            </el-form-item>
            <el-form-item label="新密码：" prop="newpassword">
                <el-input v-model="userpassword.newpassword" type="password" show-password autocomplete="off"
                    placeholder="请输入新密码" />
            </el-form-item>
            <el-form-item label="确认密码：" prop="checkpassword">
                <el-input v-model="userpassword.checkpassword" type="password" show-password autocomplete="off"
                    placeholder="请输入确认密码" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    提交
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
                <el-button @click="isVisible = false">取消</el-button>
            </div>
        </template>
    </el-dialog>
    <el-dialog v-model='isNews' title="个人消息" width="500" top="10vh" style="padding: 30px;">
        <el-scrollbar>
            <el-timeline>
                <el-timeline-item v-for="(activity, index) in activities" :key="index"
                    :icon="activity.icon == '0' ? 'el-icon-warning' : 'el-icon-success'" :color="activity.color"
                    :timestamp="activity.timestamp" size="small">
                    {{ activity.content }}
                </el-timeline-item>
                <el-timeline-item v-if="activities.length == 0" icon="el-icon-warning" timestamp="2021-05-01">
                    <div>没有任何通知</div>
                </el-timeline-item>
            </el-timeline>
        </el-scrollbar>
    </el-dialog>
</template>

<script lang="ts" setup>
import router from "@/router";
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { ref, reactive, onMounted } from 'vue';
import { changePasswordApi, changeuserApi, getMessageListApi } from '@/api/common';
const nowTime = ref("")
const complement = function (value: any) {
    return value < 10 ? `0${value}` : value;
};
const formateDate = (date: any) => {
    const time = new Date(date);
    const year = time.getFullYear();
    const month = complement(time.getMonth() + 1);
    const day = complement(time.getDate());
    const hour = complement(time.getHours());
    const minute = complement(time.getMinutes());
    const second = complement(time.getSeconds());
    return `${year}年${month}月${day}日 ${hour}:${minute}:${second}`;
}
onMounted(() => {
    setInterval(() => {
        nowTime.value = formateDate(new Date())
    })
})
const userisvisible = ref(false)
const userruleFormRef = ref<FormInstance>()
const userrules = reactive<FormRules>({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
    ],
    name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
    ],
    sex: [
        { required: true, message: '请选择性别', trigger: 'change' }
    ],
    birthday: [
        { required: true, message: '请选择生日', trigger: 'change' }
    ],
    tel: [
        { required: true, message: '请输入电话', trigger: 'blur' },
        { min: 11, max: 11, message: '长度为11个字符', trigger: 'blur' }
    ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur',] }
    ],
    role: [
        { required: true, message: '请选择角色', trigger: 'change' }
    ]
})
const user = ref({
    imgurl: "",
    username: "admin",
    name: "华华",
    sex: "1",
    birthday: "2003-01-01",
    tel: "19960702999",
    email: "3315300166@qq.com",
    role: "0",
})
const submitUserForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            changeuserApi({
                userimgurl: user.value.imgurl,
                username: user.value.username,
                name: user.value.name,
                sex: user.value.sex,
                birthday: user.value.birthday,
                tel: user.value.tel,
                email: user.value.email,
                role: user.value.role
            }).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success({ message: '修改成功！' })
                    userisvisible.value = false
                }
                else {
                    ElMessage.error({ message: '修改失败！' })
                }
            }).catch(err => {
                ElMessage.error("服务器错误！")
            })
        }
    })
}
const isNews = ref(false)
const activities = ref()
const getNews = () => {
    getMessageListApi().then(res => {
        activities.value = res.data.data
    }).catch(err => {
        ElMessage.error("服务器错误！")
    })
}
onMounted(() => {
    getNews();
})
const isVisible = ref(false)
const ruleFormRef = ref<FormInstance>()
const validateoldPass = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入原密码！'))
    } else {
        callback()
    }
}
const validatePass = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入新密码！'))
    } else {
        callback()
    }
}
const validatePass2 = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入确认密码！'))
    } else if (value !== userpassword.newpassword) {
        callback(new Error("两次密码不相同！"))
    } else {
        callback()
    }
}

const userpassword = reactive({
    oldpassword: '',
    newpassword: '',
    checkpassword: '',
})
const rules = reactive<FormRules<typeof userpassword>>({
    oldpassword: [{ validator: validateoldPass, trigger: 'blur' }],
    newpassword: [{ validator: validatePass, trigger: 'blur' }, { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }],
    checkpassword: [{ validator: validatePass2, trigger: 'blur' }],
})
const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            ElMessageBox.confirm("是否确定修改密码？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                changePasswordApi(
                    {
                        oldpassword: userpassword.oldpassword,
                        newpassword: userpassword.newpassword
                    }
                ).then(res => {
                    if (res.data.code == 200) {
                        if (res.data.data) {
                            ElMessage.success("修改成功,请重新登录！");
                            resetForm(formEl)
                            isVisible.value = false
                            router.push("/")
                        }
                        else {
                            ElMessage.warning("原密码错误！");
                            resetForm(formEl)
                        }
                    }
                    else {
                        ElMessage.error("修改失败！");
                    }
                }).catch(err => {
                    ElMessage.error("服务器错误！");
                })
            }).catch(() => {
                ElMessage({
                    type: "info",
                    message: "修改密码取消！",
                });
            });
        }
    })
}
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}
const ExitSystem = () => {
    ElMessageBox.confirm("是否退出登录", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    })
        .then(() => {
            ElMessage({
                type: "success",
                message: "退出成功",
            });
            router.push("/")
        })
        .catch(() => {
            ElMessage({
                type: "info",
                message: "取消退出",
            });
        });
}
</script>

<style scoped>
@font-face {
    font-family: electronicFont;
    src: url(../assets/font/DS-DIGIT.TTF);
}
</style>
